package com.yungam.iot_exe.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Maps;
import com.yungam.common.bean.equip.Equipment;
import com.yungam.common.bean.role.Role;
import com.yungam.common.bean.team.Team;
import com.yungam.common.bean.user.User;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.EquipmentService;
import com.yungam.common.service.RoleService;
import com.yungam.common.service.TeamService;
import com.yungam.common.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Resource
    private RoleService roleService;
    @Resource
    private EquipmentService equipmentService;

    @GetMapping("/login")
    public RetDTO<?> login(String userName, String password, String ip, HttpServletResponse response) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_name", userName);
        User user = userService.getOne(qw);
        // 查询用的角色名称和班组名称, 个人信息页面需要
        if (user.getTeamId() != null) {
            Team team = teamService.getById(user.getTeamId());
            user.setTeamName(team.getTeamName());
        }
        if (user.getRoleId() != null) {
            Role role = roleService.getById(user.getRoleId());
            user.setRoleName(role.getRoleName());
        }
        // 加密密码进行比对
        String decode = null;
        if (StringUtils.isNotEmpty(password)) decode = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!Objects.equals(decode, user.getPassword())) return RetDTO.error("用户名或密码不正确");
        // 验证成功
        String token = JWT.create().withAudience(userName)
                .withExpiresAt(new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000))
                .sign(Algorithm.HMAC256(user.getPassword()));
        response.setHeader("token", token);
        response.setHeader("Access-Control-Expose-Headers", "token");
        Map<String, Object> ans = Maps.newHashMap();
        // 添加当前登录人员
        if (StringUtils.isNotEmpty(ip)) {
            equipmentService.update(new UpdateWrapper<Equipment>().eq("equ_ip", ip)
                    .set("cur_user_id", user.getId()));
            Equipment equipment = equipmentService.getOne(new QueryWrapper<Equipment>().eq("equ_ip", ip));
            ans.put("device", equipment);
        }
        ans.put("user", user);
        return RetDTO.data(ans);
    }

    @PostMapping("/personal")
    public RetDTO<?> savePersonal(@RequestBody User user) {
        userService.updateById(user);
        User newUser = userService.getById(user.getId());
        return RetDTO.data(newUser);
    }

}
